﻿using System;
using System.Collections.Generic;
using System.Text;
using Silvermoon.Controls.Interfaces;

namespace Silvermoon.Controls
{
    internal class ControlPickerContainer : Item, IDecorator
    {
        private static readonly Stack<ControlPickerContainer> containers = new Stack<ControlPickerContainer>();

        public static Item GetNextContainer(Control control)
        {
            ControlPickerContainer container = GetNextContainer();
            container.Control = control;
            return container;
        }

        private static ControlPickerContainer GetNextContainer()
        {
            if (containers.Count > 0)
            {
                return containers.Pop();
            }
            else
            {
                return new ControlPickerContainer();
            }
        }

        private static void ReleaseContainer(ControlPickerContainer container)
        {
            containers.Push(container);
        }

        private ControlPickerContainer()
            : base()
        {
        }

        protected internal override void Release()
        {
            base.Release();
            control = null;
            ReleaseContainer(this);
        }


        private Control control;

        public Control Control
        {
            get { return control; }
            set
            {
                if (control != value)
                {
                    var oldvalue = control;
                    control = value;
                    OnControlChanged(oldvalue);
                }
            }
        }

        protected override void OnLayout()
        {
            base.OnLayout();
            if (control!=null && CheckFlag(InvalidationFlag.Layout | InvalidationFlag.Size))
            {
                control.Bounds = control.Margin.Layout(control.Bounds, this.Size);
            }
        }

        protected virtual void OnControlChanged(Control oldControl)
        {
            if (oldControl != null) oldControl.Parent = null;
            if (control != null) control.Parent = this;
            Invalidate(InvalidationFlag.Layout);
        }

        protected internal override void OnRender(Silvermoon.Core.Renderer renderer)
        {
            base.OnRender(renderer);
            if (control != null) renderer.RenderControl(control);
        }

    }
}
